package com.neuedu.projectedu.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

public class COSStorage {
    // 1. 生成 COSClient 类的对象
//    SecretId、SecretKey
    static String SECRET_ID = "AKIDdIl292SUyEEwbAdgZZEF1zqTyURALgtu";
    static String SECRET_KEY = "tHgvwiGkz18MvLUNDyXsujMksJRSIabO";
    static String BUCKET_NAME = "jixun-1304748805";
    static String REGION = "ap-beijing";

    private COSStorage() {
    }

    /**
     * 获取客户端对象
     *
     * @return
     */
    public static COSClient getInstance() {
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        Region region = new Region(REGION);
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(cred, clientConfig);
    }

    public static String localUpfile(String path) {
        // 指定要上传的文件
        File localFile = new File(path);
        // 指定要上传到 COS 上对象键
        Date date = new Date();
        String key = Long.toString(date.getTime()) + ".jpg";
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, localFile);
        PutObjectResult putObjectResult = getInstance().putObject(putObjectRequest);
//        https://yhshop-1259460414.cos.ap-beijing.myqcloud.com/001.jpeg
        return "https://" + BUCKET_NAME + ".cos." + REGION + ".myqcloud.com/" + key;
    }

    public static String upload(InputStream in, String ext,String contentType) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 设置输入流长度为500
//        objectMetadata.setContentLength(500);
        // 设置 Content type, 默认是 application/octet-stream
        objectMetadata.setContentType(contentType);
        // 指定要上传到 COS 上对象键
        Date date = new Date();
        String key = Long.toString(date.getTime()) + ext;
        PutObjectResult result = getInstance().putObject(BUCKET_NAME, key, in, objectMetadata);
        return "https://" + BUCKET_NAME + ".cos." + REGION + ".myqcloud.com/" + key;
    }

}
